//
//  CCPopoverAnimation.swift
//  SinaWebo
//
//  Created by 陶建 on 16/4/7.
//  Copyright © 2016年 taoJ. All rights reserved.
//

import UIKit

class CCPopoverAnimation: NSObject,  UIViewControllerTransitioningDelegate {
    private var isShowPopView: Bool = false
    var popViewFrame: CGRect = CGRectZero
    
    // 谁负责专场动画
    func presentationControllerForPresentedViewController(presented: UIViewController, presentingViewController presenting: UIViewController, sourceViewController source: UIViewController) -> UIPresentationController? {
        let presentationController = CCPresentationController(presentedViewController: presented, presentingViewController: presenting)
        presentationController.popViewFrame = popViewFrame
        
        return presentationController
    }
    
    func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        isShowPopView = true
        
        return self
    }
    
    func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        isShowPopView = false
        
        return self
    }
}

extension CCPopoverAnimation: UIViewControllerAnimatedTransitioning {
    func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
        return 0.25
    }
    
    func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
        if isShowPopView {
            let toView = transitionContext.viewForKey(UITransitionContextToViewKey)
            let toViewVC = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey) as! CCPopViewController
            toViewVC.delegate?.popViewControllerShow(toViewVC)
            
            toView?.layer.anchorPoint = CGPoint(x: 0.5, y: 0)
            toView?.transform = CGAffineTransformMakeScale(1, 0.0)
            let containerView = transitionContext.containerView()
            containerView?.addSubview(toView!)
            
            UIView.animateWithDuration(transitionDuration(nil), animations: {
                toView?.transform = CGAffineTransformIdentity
            }) { (_) in
                transitionContext.completeTransition(true)
            }
            return
        }
        
        let fromViewVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) as! CCPopViewController
        fromViewVC.delegate?.popViewControllerHide(fromViewVC)
        let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey)
        UIView.animateWithDuration(transitionDuration(nil), animations: {
            fromView?.transform = CGAffineTransformMakeScale(1, 0.001)
        }) { (_) in
            transitionContext.completeTransition(true)
        }
    }
}
